﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QQ.Util;
using System.Threading;
using System.Diagnostics;
using System.Xml;

namespace BlogManager
{
    public partial class MainForm : Form
    {

        private string username = "";
        private string password = "";
        private string url = "";
        private string type = "";

        private  int count=0;

        private Rectangle dragBoxFromMouseDown;
        private int rowIndexFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;


        public MainForm()
        {
            InitializeComponent();
            LoadContent();
            this.data_blog.ContextMenuStrip = this.CreateContextMenu();
            this.data_blog.ContextMenuStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStrip_ItemClicked);
            this.data_blog.ContextMenuStrip.Paint += new System.Windows.Forms.PaintEventHandler(this.contextMenuStrip_Paint);
        }


        public void LoadContent()
        {
            foreach (Blog b in ConfigXML.Content)
            {
                string[] row = { b.blogType, b.blogTitle,b.blogKeyword, b.blogUsername, b.blogPassowod, b.blogUrl,b.blogDesc };
                this.data_blog.Rows.Add(row);
            }
        }


        /// <summary>
        /// 创建右键菜单
        /// </summary>
        /// <returns></returns>
        private ContextMenuStrip CreateContextMenu()
        {
            System.Windows.Forms.ContextMenuStrip contextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
            System.Windows.Forms.ToolStripMenuItem menu_1 = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem menu_2 = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem menu_3 = new System.Windows.Forms.ToolStripMenuItem();

            System.Windows.Forms.ToolStripSeparator toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            // 
            // contextMenuStrip1
            // 
            contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { menu_1, menu_2, menu_3, toolStripSeparator1 });
            contextMenuStrip.Name = "contextMenuStrip1";
            contextMenuStrip.Size = new System.Drawing.Size(153, 120);

            menu_1.Enabled = true;
            menu_1.Name = "new";
            menu_1.Size = new System.Drawing.Size(152, 22);
            menu_1.Text = "添加     ";

            menu_2.Enabled = false;
            menu_2.Name = "modify";
            menu_2.Size = new System.Drawing.Size(152, 22);
            menu_2.Text = "修改     ";

            menu_3.Enabled = false;
            menu_3.Name = "delete";
            menu_3.Size = new System.Drawing.Size(152, 22);
            menu_3.Text = "删除     ";


            return contextMenuStrip;
        }



        /// <summary>
        /// 写配置信息函数
        /// </summary>
        public void WriteConfigure()
        {

            List<Blog> list = new List<Blog>();
            foreach (DataGridViewRow row in this.data_blog.Rows)
            {
                if (row.Cells[Cblog.Btitle].Value != null && row.Cells[Cblog.Btitle].Value.ToString() != "")
                {
                    
                    Blog blog = new Blog();
                    blog.blogTitle = row.Cells[Cblog.Btitle].Value.ToString();
                    blog.blogUrl = row.Cells[Cblog.BUrl].Value.ToString();
                    blog.blogUsername = row.Cells[Cblog.BUsername].Value.ToString();
                    blog.blogPassowod = row.Cells[Cblog.BPassword].Value.ToString();
                    blog.blogType = row.Cells[Cblog.BType].Value.ToString();
                    blog.blogDesc = row.Cells[Cblog.BDesc].Value.ToString();
                    blog.blogKeyword = row.Cells[Cblog.BKeyword].Value.ToString();
                    list.Add(blog);
                }
            }
            
            //保存配置文件
            ConfigXML.Content = list;          
        }

        private void contextMenuStrip_Paint(object sender, PaintEventArgs e)
        {
            if (sender is System.Windows.Forms.ContextMenuStrip)
            {
                bool IsSelected = this.data_blog.SelectedRows.Count == 1 ? true : false;
                ContextMenuStrip contextMenuStrip = ((System.Windows.Forms.ContextMenuStrip)sender);
                foreach (ToolStripItem item in contextMenuStrip.Items)
                {
                    item.Enabled = (item.Name == "edit" || item.Name == "del") ? IsSelected : true;
                }
            }
        } 
     

        /// <summary>
        /// 右键菜单元素单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuStrip_ItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {
            try
            {
                DataGridViewRow row = null;
                if (this.data_blog.SelectedRows.Count == 1)
                {
                    row = this.data_blog.SelectedRows[0];
                }
                if ("new" == e.ClickedItem.Name)
                {
                    AddForm quickForm = new AddForm();
                    quickForm.ReturnHandler += new Action<Blog>(delegate(Blog b)
                    {
                        int index = this.data_blog.Rows.Add();
                        if (index > -1)
                        {
                            this.data_blog.Rows[index].Cells[Cblog.Btitle].Value = b.blogTitle;
                            this.data_blog.Rows[index].Cells[Cblog.BUrl].Value = b.blogUrl;
                            this.data_blog.Rows[index].Cells[Cblog.BUsername].Value = b.blogUsername;
                            this.data_blog.Rows[index].Cells[Cblog.BPassword].Value = b.blogPassowod;
                            this.data_blog.Rows[index].Cells[Cblog.BType].Value = b.blogType;
                            this.data_blog.Rows[index].Cells[Cblog.BDesc].Value = b.blogDesc;
                            this.data_blog.Rows[index].Cells[Cblog.BKeyword].Value = b.blogKeyword;

                        }
                        WriteConfigure();
                    });
                    quickForm.ShowDialog();
                }
                else if ("modify" == e.ClickedItem.Name)
                {
                    if (row != null)
                    {
                        AddForm quickForm = new AddForm();
                        Blog blog = new Blog(); 
                        blog.blogTitle = row.Cells[Cblog.Btitle].Value.ToString();
                        blog.blogUrl = row.Cells[Cblog.BUrl].Value.ToString();
                        blog.blogUsername = row.Cells[Cblog.BUsername].Value.ToString();
                        blog.blogPassowod = row.Cells[Cblog.BPassword].Value.ToString();
                        blog.blogType = row.Cells[Cblog.BType].Value.ToString();
                        blog.blogDesc = row.Cells[Cblog.BDesc].Value.ToString();
                        blog.blogKeyword = row.Cells[Cblog.BKeyword].Value.ToString(); 

                        quickForm.Content = blog;
                        quickForm.ReturnHandler += new Action<Blog>(delegate(Blog b)
                        {
                            row.Cells[Cblog.Btitle].Value = b.blogTitle;
                            row.Cells[Cblog.BUrl].Value = b.blogUrl;
                            row.Cells[Cblog.BUsername].Value = b.blogUsername;
                            row.Cells[Cblog.BPassword].Value = b.blogPassowod;
                            row.Cells[Cblog.BType].Value = b.blogType;

                            row.Cells[Cblog.BKeyword].Value = b.blogKeyword;

                            row.Cells[Cblog.BDesc].Value = b.blogDesc; 
                            WriteConfigure();
                        });

                        quickForm.ShowDialog();
                    }
                }
                else if ("delete" == e.ClickedItem.Name)
                {
                    if (row != null)
                    {
                        this.data_blog.Rows.RemoveAt(row.Index);
                        WriteConfigure();
                    }
                }

            }
            catch(Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
        /// <summary>
        /// 点击查看按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void data_blog_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView DataGridView1 = (DataGridView)sender;
            if (e.ColumnIndex == 7)
            {
                string Password = DataGridView1.CurrentRow.Cells[Cblog.BPassword].Value.ToString();
                string Username = DataGridView1.CurrentRow.Cells[Cblog.BUsername].Value.ToString();
                string Url = DataGridView1.CurrentRow.Cells[Cblog.BUrl].Value.ToString();
                string type = DataGridView1.CurrentRow.Cells[Cblog.BType].Value.ToString();
                AutoLogin(Username, Password, type, Url);
                 
            } 
        }

        /// <summary>
        /// 转发自动登录的操作
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="type"></param>
        /// <param name="url"></param>
        private void AutoLogin(string username, string password, string type, string url)
        {
            tab_blog.SelectTab(1);
            this.password = password;
            this.username = username;
            this.url = url;
            this.type = type;
            this.count = 1;

            if (type == "Facebook")
            {
                webBrowser.Navigate(new Blog().FacebookUrl);
            }          
            else if (type == "Twitter")
            {
                webBrowser.Url = new Uri(new Blog().TwitterUrl);
            }
            else if (type == "Plurk")
            {
                webBrowser.Url = new Uri(new Blog().PlurkUrl);
            }
            else if (type == "Yahoo")
            {
                webBrowser.Url = new Uri(new Blog().YahooUrl);
            }
            else if (type == "Google")
            {
                webBrowser.Url = new Uri(new Blog().GoogleUrl);
            }
            else if (type == "weibo")
            {
                webBrowser.Url = new Uri(new Blog().weibo);
            }
            else if (type == "msn")
            {
                webBrowser.Url = new Uri(new Blog().msn);
            }
            else
            {
                webBrowser.Url = new Uri(url);
            }

        }


 
  



        /// <summary>
        /// 登录facebook
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void LoginFacebook()
        {
            webBrowser.Document.GetElementById("email").InnerText = this.username;
            webBrowser.Document.GetElementById("pass").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("login_form");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("submit");
            }
        }


        /// <summary>
        /// 登录twitter
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void LoginTwitter()
        {
          
            // webBrowser.Document.All["session[username_or_email]"].InnerText = this.username;
            // webBrowser.Document.All["session[password]"].InnerText = this.password;
            findNodeByName(1, "input").InnerText = this.username;
            findNodeByName(2, "input").InnerText = this.password;


             findNodeByName(5, "input").InnerText = this.username;
             findNodeByName(6, "input").InnerText = this.password;
            HtmlElement btn = findForm(1); 
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("submit");
            }
        }

        private void LoginPlurk()
        {
            webBrowser.Document.GetElementById("first").InnerText = this.username;
              webBrowser.Document.All["password"].InnerText=this.password;
              HtmlElement btn = findForm(0);
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("submit");
            }
        }


        /// <summary>
        /// 登录weibo
        /// </summary>
        private void LoginWeibo()
        {
            webBrowser.Document.GetElementById("loginname").InnerText = this.username;

            webBrowser.Document.GetElementById("password").InnerText = this.username;
            //webBrowser.Document.All["password"].InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("login_submit_btn");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }


        /// <summary>
        /// 登录MSN
        /// </summary>
        private void LoginMsn()
        {

            webBrowser.Document.All["login"].InnerText = this.username;
            webBrowser.Document.All["passwd"].InnerText = this.password;


            HtmlElement btn = webBrowser.Document.All["SI"];
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }


        /// <summary>
        /// 获取form，便于提交form
        /// </summary>
        /// <param name="num">form的位置</param>
        /// <returns></returns>
        private HtmlElement findForm(int num)
        {
            HtmlElement el = null;
            HtmlDocument htm = this.webBrowser.Document;
            HtmlElementCollection all = htm.Forms;
            for (int i = 0; i < all.Count; i++)
            {
                HtmlElement elem = all[i];
                elem.Name.ToString();
              
            }
            return all[num];
        }


        private HtmlElement findNodeByName(int num, string tagName)
        {
            HtmlElement el = null;
            HtmlDocument htm = this.webBrowser.Document;
            HtmlElementCollection all = htm.GetElementsByTagName(tagName);
            for (int i = 0; i < all.Count; i++)
            {
                HtmlElement elem = all[i];

                Console.WriteLine(elem.Name.ToString()+"=="+i+"==\r\n");

            }
            return all[num];
        }


        private HtmlElement FindNode(string tag,string attr,string value)
        {
            HtmlElement el=null;
            HtmlDocument htm = this.webBrowser.Document;
            HtmlElementCollection all = htm.All;
          
            for (int i = 0; i < all.Count; i++)
            {
                HtmlElement elem = all[i];
           
                if (elem.TagName.ToLower() ==tag)
                { 
                    if (value == "")
                    {
                        el = elem;
                        break;
                    }
                    else
                    { 
                        string attrstr = elem.GetAttribute(attr);
                        if (attrstr == value)
                        {
                            el = elem;
                            break;
                        }
                    }
                  
                }
            }

            return el;
        }

      

        /// <summary>
        /// 登录google的gmail
        /// </summary>
        private void LoginGoogle()
        {

            webBrowser.Document.GetElementById("Email").InnerText = this.username;
            webBrowser.Document.GetElementById("Passwd").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("signIn");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }

        }


        /// <summary>
        /// 登录痞客帮
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void Loginblogger()
        {
            webBrowser.Document.GetElementById("Email").InnerText = this.username;
            webBrowser.Document.GetElementById("Passwd").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("signIn");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }

        /// <summary>
        /// 登录雅虎
        /// </summary>
        private void LoginYahoo()
        {
            webBrowser.Document.GetElementById("username").InnerText = this.username;
            webBrowser.Document.GetElementById("passwd").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById(".save");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (this.count == 1)
            {
                if (this.type == "Facebook")
                {
                    LoginFacebook();
                }
                else if (type == "Twitter")
                {
                    LoginTwitter();
                }
                else if (type == "Plurk")
                {
                    LoginPlurk();
                }
                else if (type == "Google")
                {
                    LoginGoogle();
                }
                else if (type == "Yahoo")
                {
                    LoginYahoo();
                }
                else if (type == "weibo")
                {
                    LoginWeibo();
                }

                else if (type == "msn")
                {
                    LoginMsn();
                } 
                this.count++;
            }
        }

        private void data_blog_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                // If the mouse moves outside the rectangle, start the drag.
                if (dragBoxFromMouseDown != Rectangle.Empty &&
                    !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {

                    // Proceed with the drag and drop, passing in the list item.                   
                    DragDropEffects dropEffect = data_blog.DoDragDrop(
                   data_blog.Rows[rowIndexFromMouseDown],
                   DragDropEffects.Move);
                }
            }

        }

        private void data_blog_MouseDown(object sender, MouseEventArgs e)
        {
            // Get the index of the item the mouse is below.
            rowIndexFromMouseDown = data_blog.HitTest(e.X, e.Y).RowIndex;

            if (rowIndexFromMouseDown != -1)
            {
                // Remember the point where the mouse down occurred. 
                // The DragSize indicates the size that the mouse can move 
                // before a drag event should be started.               
                Size dragSize = SystemInformation.DragSize;

                // Create a rectangle using the DragSize, with the mouse position being
                // at the center of the rectangle.
                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
                                                               e.Y - (dragSize.Height / 2)),
                                   dragSize);
            }
            else
                // Reset the rectangle if the mouse is not over an item in the ListBox.
                dragBoxFromMouseDown = Rectangle.Empty;

        }

        private void data_blog_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;

        }

        private void data_blog_DragDrop(object sender, DragEventArgs e)
        {
            // The mouse locations are relative to the screen, so they must be
            // converted to client coordinates.
            Point clientPoint = data_blog.PointToClient(new Point(e.X, e.Y));

            // Get the row index of the item the mouse is below.
            rowIndexOfItemUnderMouseToDrop =
                data_blog.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

            // If the drag operation was a move then remove and insert the row.
            if (e.Effect == DragDropEffects.Move)
            {
                DataGridViewRow rowToMove = e.Data.GetData(
                   typeof(DataGridViewRow)) as DataGridViewRow;
                data_blog.Rows.RemoveAt(rowIndexFromMouseDown);
                data_blog.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);
                WriteConfigure();

            }

        }
    }
}
